package com.example.service.Impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.aliyun.service.UploadService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.RedisFileConstant;
import com.example.context.BaseContext;
import com.example.mapper.AdminMapper;
import com.example.pojo.dto.AccessDTO;
import com.example.pojo.entity.Admin;
import com.example.pojo.entity.Project;
import com.example.pojo.entity.Team;
import com.example.pojo.utils.SendMessage;
import com.example.service.ContractService;
import com.example.service.EntrustService;
import com.example.service.ProjectService;
import com.example.mapper.ContractMapper;
import com.example.pojo.entity.Contract;
import com.example.service.TeamService;
import com.example.utils.SendMessageUtils;
import com.example.utils.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;


/**
 * TODO
 *
 * @author ding
 * @since 2024/6/2
 */
@Service
@DS("master")
public class ContractServiceImp extends ServiceImpl<ContractMapper, Contract> implements ContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private TeamService teamService;

    @Autowired
    private @Lazy ProjectService projectService;

    @Autowired
    private EntrustService entrustService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private SendMessageUtils sendMessageUtils;

    /**
     * 根据id删除合同信息
     * @param id
     */
    @Transactional
    public void deleteById(Integer id) {
        UpdateWrapper<Contract> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", 1)
                .set("deleted_id", Math.toIntExact(BaseContext.getCurrentId()))
                .eq("id" ,id);

        contractMapper.update(updateWrapper);
    }

    /**
     * 根据id集合批量删除合同信息
     */
    @Transactional
    public void delBatch(List<Integer> ids) {
        for (Integer id : ids) {
            deleteById(id);
        }
    }

    /**
     * 新增合同信息
     */
    @Transactional
    public void add(AccessDTO accessDTO) throws IOException {
        Team team = teamService.selectById(accessDTO.getTeamId());
        Contract contract = Contract.builder()
                .entrustId(1)
                .teamId(accessDTO.getTeamId())
                .createTime(LocalDateTime.now())
                .status(0)
                .contractCode(accessDTO.getContractCode())
                .contractor(accessDTO.getContractor())
                .phone(accessDTO.getPhone())
                .isDeleted(0)
                .entrustName(accessDTO.getEntrustName())
                .investment(BigDecimal.valueOf(accessDTO.getBudget()))
                .projectId(accessDTO.getProjectId())
                .projectName(accessDTO.getProjectName())
                .teamName(team.getName())
                .version(0)
                .build();

        accessDTO.setTeamName(team.getName());

        WordUtils wordUtils = new WordUtils();
        String filePath = wordUtils.createWord(accessDTO);
        File pdf = new File(filePath);
        FileInputStream fis = new FileInputStream(pdf);
        MultipartFile file = new MockMultipartFile(pdf.getName(), pdf.getName(), ContentType.MULTIPART.toString(), fis);
        String url = uploadService.upload(file);

        contract.setFilePath(url);
        contractMapper.insert(contract);

        //生成合同文件后，向施工队队长发送邮件
        //获取队长信息
        Admin captain = adminMapper.selectById(team.getCaptainId());
        SendMessage sendMessage = new SendMessage();
        sendMessage.setTo(captain.getEmail());

        String content = "您好，" + team.getName() + "施工队的队长" + captain.getName()
                + "，您的施工队刚才已接取项目" + accessDTO.getProjectName() + "，"
                + "<h4 style='color:blue'><a href='" + url + "'>这是您的合同文件，请妥善保管</a></h4>";
        sendMessage.setContent(content);
        sendMessage.setSubject("项目接取");

        //发送邮件
        sendMessageUtils.sendHTMLMessage(sendMessage);
    }

    /**
     * 获取全部合同信息
     */
    public List<Contract> selectAll() {
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted",0);
        return list(queryWrapper);
    }

    public Page<Contract> selectByPage(Integer pageNum, Integer pageSize, String teamName, String projectName, String order) {
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        if (order != null){
            if (order.equals("ascend")){
                queryWrapper.orderByAsc("create_time");
            }
            if (order.equals("descend")){
                queryWrapper.orderByDesc("create_time");
            }
        }
        if (StrUtil.isNotBlank(teamName)){
            Team team = teamService.selectByTeamName(teamName);
            queryWrapper.eq("team_id",team.getId());
        }
        if (StrUtil.isNotBlank(projectName)){
            Project project = projectService.selectByName(projectName);
            queryWrapper.eq("project_id",project.getId());
        }

        queryWrapper.eq("is_deleted",0);
        Page<Contract> page = contractMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);

        List<Contract> records = page.getRecords();
        for (Contract record : records) {
            record.setProjectName(projectService.getById(record.getProjectId()).getName());
            record.setTeamName(teamService.getById(record.getTeamId()).getName());
            record.setEntrustName(entrustService.getById(record.getEntrustId()).getName());
        }
        page.setRecords(records);
        return page;
    }
}
